package com.ds.yuntukubackend.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ds.yuntukubackend.annotation.AuthCheck;
import com.ds.yuntukubackend.common.BaseResponse;
import com.ds.yuntukubackend.common.DeleteRequest;
import com.ds.yuntukubackend.common.ResultUtils;
import com.ds.yuntukubackend.contant.UserConstant;
import com.ds.yuntukubackend.exception.BusinessException;
import com.ds.yuntukubackend.exception.ErrorCode;
import com.ds.yuntukubackend.exception.ThrowUtils;
import com.ds.yuntukubackend.model.dto.picture.*;
import com.ds.yuntukubackend.model.dto.space.SpaceLevel;
import com.ds.yuntukubackend.model.entity.Picture;
import com.ds.yuntukubackend.model.entity.User;
import com.ds.yuntukubackend.model.enums.PictureReviewStatusEnum;
import com.ds.yuntukubackend.model.enums.SpaceLevelEnum;
import com.ds.yuntukubackend.model.vo.PictureTagCategory;
import com.ds.yuntukubackend.model.vo.PictureVO;
import com.ds.yuntukubackend.service.PictureService;
import com.ds.yuntukubackend.service.UserService;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Slf4j
@RestController
@RequestMapping("/picture")
public class PictureController {

    @Resource
    private UserService userService;
    @Resource
    private PictureService pictureService;





    private final Cache<String, String> LOCAL_CACHE =
            Caffeine.newBuilder().initialCapacity(1024)
                    .maximumSize(10000L)
                    // 缓存 5 分钟移除
                    .expireAfterWrite(5L, TimeUnit.MINUTES)
                    .build();


    /**
     * 上传图片（可重新上传）
     * @param multipartFile 文件
     * @param pictureUploadRequest 图片上传请求（图片id:用于修改）
     * @param request 请求
     * @return
     */
    @PostMapping("/upload")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<PictureVO> uploadPicture(
            @RequestPart("file") MultipartFile multipartFile,
            PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {

        User loginUser = userService.getLoginUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 通过url上传图片（可重新上传）
     * @param pictureUploadRequest 图片上传请求（图片id:用于修改）
     * @param request 请求
     * @return
     */
    @PostMapping("/upload/url")
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<PictureVO> uploadPictureByUrl(
            @RequestBody PictureUploadRequest pictureUploadRequest,
            HttpServletRequest request) {

        User loginUser = userService.getLoginUser(request);
        String fileUrl = pictureUploadRequest.getFileUrl();
        PictureVO pictureVO = pictureService.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 删除图片
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        pictureService.deletePicture(deleteRequest.getId(), loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 更新图片（仅管理员可用）
     * @param pictureUpdateRequest
     * @param request
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest,
                                               HttpServletRequest request) {
        if (pictureUpdateRequest == null || pictureUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureUpdateRequest, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureUpdateRequest.getTags()));
        // 数据校验
        pictureService.validPicture(picture);
        // 判断是否存在
        long id = pictureUpdateRequest.getId();
        Picture oldPicture = pictureService.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        //获取登录用户
        User loginUser = userService.getLoginUser(request);
        //补充待审核参数
        pictureService.fillReviewParams(oldPicture,loginUser);
        // 操作数据库
        boolean result = pictureService.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 根据 id 获取图片（仅管理员可用）
     */
    @GetMapping("/get")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Picture> getPictureById(long id, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        Picture picture = pictureService.getPictureById(id, loginUser);
        return ResultUtils.success(picture);
    }

    /**
     * 根据 id 获取图片（关联查询用户信息）
     */
    @GetMapping("/get/vo")
    public BaseResponse<PictureVO> getPictureVOById(long id, HttpServletRequest request) {
        User loginUser = userService.getLoginUser(request);
        Picture picture = pictureService.getPictureById(id, loginUser);
        // 获取封装类
        return ResultUtils.success(pictureService.getPictureVO(picture));
    }

    /**
     * 分页获取图片列表（仅管理员可用）
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        return ResultUtils.success(picturePage);
    }

    /**
     * 分页获取图片列表（封装类）
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<PictureVO>> listPictureVOByPage(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                             HttpServletRequest request) {

        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        Page<Picture> picturePage = pictureService.listPictureByPage(pictureQueryRequest,loginUser);
        // 获取封装类
        return ResultUtils.success(pictureService.getPictureVOPage(picturePage));
    }
    /**
     * 分页获取图片列表（封装类,有缓存）
     */
    @PostMapping("/list/page/vo/cache")
    public BaseResponse<Page<PictureVO>> listPictureVOByPageWithCache(@RequestBody PictureQueryRequest pictureQueryRequest) {
        long current = pictureQueryRequest.getCurrent();
        long size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);

        //普通用户默认只能看到审核通过的数据
        pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
        //先查询缓存，再查询数据库
        //构建缓存的key
        String queryRequest = JSONUtil.toJsonStr(pictureQueryRequest);
        String hashKey = DigestUtil.md5Hex(queryRequest);//压缩
//        String redisKey = String.format("yunTuKu:listPictureVOByPage:%s",hashKey);
        String cacheKey = String.format("listPictureVOByPage:%s",hashKey);
        //操作redis,从缓存中查询
        String cachedValue = LOCAL_CACHE.getIfPresent(cacheKey);//本地缓存
//        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
//        String cachedValue = opsForValue.get(cacheKey); //redis
        if(StrUtil.isNotBlank(cachedValue)){
            //反序列化
            Page<PictureVO> cachedPage = JSONUtil.toBean(cachedValue, Page.class);
            return ResultUtils.success(cachedPage);
        }
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
                pictureService.getQueryWrapper(pictureQueryRequest));
        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage);
        //存入redis缓存
        String cacheValue = JSONUtil.toJsonStr(pictureVOPage);
        //设置缓存时间过期时间 5-10分钟，防止太多数据同一时间失效导致缓存雪崩
//        int cacheExpireTime = 300 + RandomUtil.randomInt(0,300);
//        opsForValue.set(cacheKey,cacheValue,cacheExpireTime, TimeUnit.SECONDS);
        LOCAL_CACHE.put(cacheKey,cacheValue);
        // 获取封装类
        return ResultUtils.success(pictureVOPage);
    }

//    /**
//     * 分页获取图片列表（封装类,有缓存）
//     */
//    @PostMapping("/list/page/vo/cacheAndRedis")
//    public BaseResponse<Page<PictureVO>> listPictureVOByPageWithTwoCache(@RequestBody PictureQueryRequest pictureQueryRequest,
//                                                                      HttpServletRequest request) {
//        long current = pictureQueryRequest.getCurrent();
//        long size = pictureQueryRequest.getPageSize();
//        // 限制爬虫
//        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
//
//        //普通用户默认只能看到审核通过的数据
//        pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
//        //先查询缓存，再查询数据库
//        //构建缓存的key
//        String queryRequest = JSONUtil.toJsonStr(pictureQueryRequest);
//        String hashKey = DigestUtil.md5Hex(queryRequest);//压缩
////        String redisKey = String.format("yunTuKu:listPictureVOByPage:%s",hashKey);
//        String cacheKey = String.format("yunTuKu:listPictureVOByPage:%s",hashKey);
//        //1.先从本地缓存中查询
//        String cachedValue = LOCAL_CACHE.getIfPresent(cacheKey);//本地缓存
//        if(StrUtil.isNotBlank(cachedValue)){
//            //反序列化
//            Page<PictureVO> cachedPage = JSONUtil.toBean(cachedValue, Page.class);
//            return ResultUtils.success(cachedPage);
//        }
//        //2.再从redis缓存中查询
//        ValueOperations<String, String> opsForValue = stringRedisTemplate.opsForValue();
//        cachedValue = opsForValue.get(cacheKey);
//        if(StrUtil.isNotBlank(cachedValue)){
//            //更新本地缓存
//            LOCAL_CACHE.put(cacheKey,cachedValue);
//            //反序列化
//            Page<PictureVO> cachedPage = JSONUtil.toBean(cachedValue, Page.class);
//            return ResultUtils.success(cachedPage);
//        }
//        // 查询数据库
//        Page<Picture> picturePage = pictureService.page(new Page<>(current, size),
//                pictureService.getQueryWrapper(pictureQueryRequest));
//        Page<PictureVO> pictureVOPage = pictureService.getPictureVOPage(picturePage, request);
//        //存入redis缓存
//        String cacheValue = JSONUtil.toJsonStr(pictureVOPage);
//        //设置缓存时间过期时间 5-10分钟，防止太多数据同一时间失效导致缓存雪崩
//        int cacheExpireTime = 300 + RandomUtil.randomInt(0,300);
//        opsForValue.set(cacheKey,cacheValue,cacheExpireTime, TimeUnit.SECONDS);
//        LOCAL_CACHE.put(cacheKey,cacheValue);
//        // 获取封装类
//        return ResultUtils.success(pictureVOPage);
//    }
//
//
//    /**
//     * 分页获取图片列表（封装类,有缓存）
//     */
//    @PostMapping("/list/page/vo/test")
//    public BaseResponse<Page<PictureVO>> listPictureVOByPageWith(@RequestBody PictureQueryRequest pictureQueryRequest,
//                                                                 HttpServletRequest request, RedisCacheStrategy redisCacheStrategy) {
//
//        return cacheContext.listPictureVOByPageWithCacheStrategy(pictureQueryRequest, request, redisCacheStrategy);
//
//    }


    /**
     * 编辑图片（给用户使用）
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest, HttpServletRequest request) {
        if (pictureEditRequest == null || pictureEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        boolean result = pictureService.editPicture(pictureEditRequest, loginUser);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }


    /**
     * 假数据-标签
     * @return
     */
    @GetMapping("/tag_category")
    public BaseResponse<PictureTagCategory> listPictureTagCategory() {
        PictureTagCategory pictureTagCategory = new PictureTagCategory();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategory);
    }

    /**
     * 审核图片
     */
    @PostMapping("/review")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> doPictureReview(@RequestBody PictureReviewRequest pictureReviewRequest, HttpServletRequest request) {

        ThrowUtils.throwIf(pictureReviewRequest == null, ErrorCode.OPERATION_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.doPictureReview(pictureReviewRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 批量抓取并创建图片
     * @param pictureUploadByBatchRequest
     * @param request
     * @return
     */
    @PostMapping("/upload/batch")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Integer> uploadPictureByBatch(
            @RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest,
            HttpServletRequest request
    ) {
        ThrowUtils.throwIf(pictureUploadByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        int uploadCount = pictureService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser);
        return ResultUtils.success(uploadCount);
    }

    //获取空间级别列表，便于前端展示
    @GetMapping("/list/level")
    public BaseResponse<List<SpaceLevel>> ListSpaceLevel(){
        List<SpaceLevel> spaceLevelList = Arrays.stream(SpaceLevelEnum.values())
                .map(spaceLevelEnum -> new SpaceLevel(
                            spaceLevelEnum.getValue(),
                            spaceLevelEnum.getText(),
                            spaceLevelEnum.getMaxCount(),
                            spaceLevelEnum.getMaxSize()
                    )).collect(Collectors.toList());
        return ResultUtils.success(spaceLevelList);
    }
}
